package com.wephone.Student;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.google.gson.Gson;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.Constant;
import com.wephone.Student.huanxin.domain.User;
import com.wephone.Student.ui.BaseActivity;
import com.wephone.Student.ui.LoginActivity;
import com.wephone.Student.ui.MainTabBar;
import com.wephone.Student.util.ShareReferenceUtil;

public class WelcomeActivity extends BaseActivity{
	public static boolean isForeground = false;
	private ViewPager viewPager;
	private List<View> mSubViews = new ArrayList<View>();
	private List<ImageView> statusBarList = new ArrayList<ImageView>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		
//		JPushInterface.init(this);
//		JPushInterface.setLatestNotifactionNumber(getApplicationContext(), 1);
//		registerMessageReceiver();
//		setPushNotificationStyle();
//		if(TextUtils.isEmpty(ShareReferenceUtil.getUserId(getApplicationContext()))){
//			JPushInterface.stopPush(getApplicationContext());
//		}else{
//			setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
//		}
		
		
		

		init();
		
		// 以apikey的方式登录，一般放在主Activity的onCreate中
//		PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,Utils.getMetaValue(WelcomeActivity.this, "api_key"));
		
		//设置自定义的通知样式，如果想使用系统默认的可以不加这段代码
//		Resources resource = this.getResources();
//		String pkgName = this.getPackageName();
//        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//        		resource.getIdentifier("notification_custom_builder", "layout", pkgName), 
//        		resource.getIdentifier("notification_icon", "id", pkgName), 
//        		resource.getIdentifier("notification_title", "id", pkgName), 
//        		resource.getIdentifier("notification_text", "id", pkgName));
//        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//        cBuilder.setNotificationDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
//        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//        cBuilder.setLayoutDrawable(resource.getIdentifier("simple_notification_icon", "drawable", pkgName));
//		PushManager.setNotificationBuilder(this, 1, cBuilder);
	}

	@Override
	public void onStart() {
		super.onStart();

//		PushManager.activityStarted(this);
	}
	
	@Override
	protected void onResume() {
		isForeground = true;
		super.onResume();
		
	}


	@Override
	protected void onPause() {
		isForeground = false;
		super.onPause();
	}


	@Override
	public void onStop() {
		super.onStop();
//		PushManager.activityStoped(this);
	}
	
	@Override
	protected void onDestroy() {
//		unregisterReceiver(mMessageReceiver);
		super.onDestroy();
	}
	
	private void init(){
		statusBarList.add((ImageView)findViewById(R.id.bar_status_0));
		statusBarList.add((ImageView)findViewById(R.id.bar_status_1));
		statusBarList.add((ImageView)findViewById(R.id.bar_status_2));
//		statusBarList.add((ImageView)findViewById(R.id.bar_status_3));
//		statusBarList.add((ImageView)findViewById(R.id.bar_status_4));
//		statusBarList.add((ImageView)findViewById(R.id.bar_status_5));
		
		viewPager = (ViewPager)findViewById(R.id.viewpager);
		View v0 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
		ImageView img0 = (ImageView)v0.findViewById(R.id.wel_image_item);
		img0.setImageResource(R.drawable.bg_loading00);
		mSubViews.add(v0);
		View v1 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
		ImageView img1 = (ImageView)v1.findViewById(R.id.wel_image_item);
		img1.setImageResource(R.drawable.bg_loading01);
		mSubViews.add(v1);
//		View v2 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
//		ImageView img2 = (ImageView)v2.findViewById(R.id.wel_image_item);
//		img2.setImageResource(R.drawable.bg_loading02);
//		Button loginBtn2 = (Button)v2.findViewById(R.id.btn_login);
//		loginBtn2.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
//				finish();
//			}
//		});
//		Button registerBtn2 = (Button)v2.findViewById(R.id.btn_register);
//		registerBtn2.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
//				finish();
//			}
//		});
//		mSubViews.add(v2);
		
//		View v3 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
//		ImageView img3 = (ImageView)v3.findViewById(R.id.wel_image_item);
//		img3.setImageResource(R.drawable.bg_loading03);
//		Button loginBtn3 = (Button)v3.findViewById(R.id.btn_login);
//		loginBtn3.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
//				finish();
//			}
//		});
//		Button registerBtn3 = (Button)v3.findViewById(R.id.btn_register);
//		registerBtn3.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
//				finish();
//			}
//		});
//		mSubViews.add(v3);
//		View v4 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
//		ImageView img4 = (ImageView)v4.findViewById(R.id.wel_image_item);
//		img4.setImageResource(R.drawable.bg_loading04);
//		Button loginBtn4 = (Button)v4.findViewById(R.id.btn_login);
//		loginBtn4.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
//				finish();
//			}
//		});
//		Button registerBtn4 = (Button)v4.findViewById(R.id.btn_register);
//		registerBtn4.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
//				finish();
//			}
//		});
//		mSubViews.add(v4);
		View v5 = getLayoutInflater().inflate(R.layout.include_welcome_page_item, null);
		ImageView img5 = (ImageView)v5.findViewById(R.id.wel_image_item);
		img5.setImageResource(R.drawable.bg_loading02);
		Button loginBtn5 = (Button)v5.findViewById(R.id.btn_login);
		loginBtn5.setVisibility(View.VISIBLE);
		loginBtn5.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
				finish();
			}
		});
//		Button loginBtn4 = (Button)v4.findViewById(R.id.btn_login);
//		loginBtn4.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),LoginActivity.class));
//				finish();
//			}
//		});
//		Button registerBtn4 = (Button)v4.findViewById(R.id.btn_register);
//		registerBtn4.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
//				finish();
//			}
//		});
		mSubViews.add(v5);
		viewPager.setAdapter(new ViewAdapter());
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				for(int i=0;i<statusBarList.size();i++){
					if(i==arg0){
						statusBarList.get(i).setImageResource(R.drawable.bg_pagepoint01);
					}else{
						statusBarList.get(i).setImageResource(R.drawable.bg_pagepoint02);
					}
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		
		String userInfoJson = ShareReferenceUtil.getUserInfoJson(getApplicationContext());
		if(!TextUtils.isEmpty(userInfoJson)){
			Gson gson = new Gson();
			final UserInfoData infoData = gson.fromJson(userInfoJson, UserInfoData.class);
//			BaseActivity.myInfo = infoData;
			ShareReferenceUtil.saveUserId(getApplicationContext(), infoData.getuId());
//			setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
			String infoJson = gson.toJson(infoData);
			ShareReferenceUtil.saveUserInfoJson(getApplicationContext(), infoJson);
			
//			System.out.println("-----1-----"+infoData.getuId());
//			System.out.println("-----2-----"+infoData.getuPwd());
			
//			System.out.println("----BroadcastAction----"+EMChatManager.getInstance().getNewMessageBroadcastAction());
			
			//login huanxin account
			EMChatManager.getInstance().login(infoData.getuId(), infoData.getuPwd(), new EMCallBack() {
				@Override
				public void onError(int arg0, final String errorMsg) {
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(WelcomeActivity.this, "登录聊天服务器失败，您将收不到消息", Toast.LENGTH_SHORT).show();
						}
					});
				}

				@Override
				public void onProgress(int arg0, String arg1) {
				}

				@Override
				public void onSuccess() {
					// 登陆成功，保存用户名密码
					BaseApplication.getInstance().setUserName(infoData.getuId());
					BaseApplication.getInstance().setPassword(infoData.getuPwd());
					runOnUiThread(new Runnable() {
						public void run() {
							EMGroupManager.getInstance().loadAllGroups();
							EMChatManager.getInstance().loadAllConversations();
							
						}
					});
					processContactsAndGroups();
//					try {
//						// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
//						List<String> usernames = EMChatManager.getInstance().getContactUserNames();
//						System.out.println("-----usernames.size()-----"+usernames.size());
//						Map<String, User> userlist = new HashMap<String, User>();
//						for (String username : usernames) {
//							User user = new User();
//							user.setUsername(username);
//							setUserHearder(username, user);
//							userlist.put(username, user);
//						}
//						// 添加user"新的朋友"
//						User newFriends = new User();
//						newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
//						newFriends.setNick("新的朋友");
//						newFriends.setHeader("");
//						userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
					
					
					
//					List<String> userNameList = EMChatDB.getInstance().findAllParticipantsWithMsg();
//					for(String userName:userNameList){
//						User newFriends = new User();
//						newFriends.setUsername(userName);
//						newFriends.setNick("nick"+userName);
//						newFriends.setHeader("");
//						userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
//					}
					
//						//添加"群聊"
////						User groupUser = new User();
////						groupUser.setUsername(Constant.GROUP_USERNAME);
////						groupUser.setNick("群聊");
////						groupUser.setHeader("");
////						userlist.put(Constant.GROUP_USERNAME, groupUser);
//						
//						//存入内存
//						BaseApplication.getInstance().setContactList(userlist);
//						// 存入db
//						UserDao dao = new UserDao(MainActivity.this);
//						List<User> users = new ArrayList<User>(userlist.values());
//						dao.saveContactList(users);
//
//						// 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
//						EMGroupManager.getInstance().getGroupsFromServer();
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
					
					EMChat.getInstance().setAppInited();
					
//					runOnUiThread(new Runnable() {
//						public void run() {
//							Toast.makeText(MainActivity.this, "登录聊天服务器成功", Toast.LENGTH_SHORT).show();
//						}
//					});
				}
			});
			//app初始化完毕
//			EMChat.getInstance().setAppInited();
			
			startActivity(new Intent(getApplicationContext(),MainTabBar.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
	                Intent.FLAG_ACTIVITY_CLEAR_TASK |
	                Intent.FLAG_ACTIVITY_NEW_TASK));
			finish();
		}
		
		initCountryList(getApplicationContext());
	}

	private void processContactsAndGroups(){
        
	     // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
	        try {
	            EMGroupManager.getInstance().getGroupsFromServer();
	            Map<String, User> userlist = new HashMap<String, User>();
	     
	            // 添加user"申请与通知"
	            User newFriends = new User();
	            newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
	            String strChat = "系统消息";
	            newFriends.setNick(strChat);

	            userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
	            
	            BaseApplication.getInstance().setContactList(userlist);
	        } catch (EaseMobException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	    }
	private class ViewAdapter extends PagerAdapter {
		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mSubViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mSubViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int position) {
			((ViewPager) arg0).addView(mSubViews.get(position), 0);
			
			return mSubViews.get(position);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}
	
	private static long backClickTime = -1;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			 long nowTime = System.currentTimeMillis();
				if(backClickTime<=0 || nowTime-backClickTime>2000){
					backClickTime = nowTime;
					Toast.makeText(getApplicationContext(), "再按一次 退出程序", Toast.LENGTH_SHORT).show();
				}else{
					finish();
				}
          return true; 
        }
        return super.onKeyDown(keyCode, event); 
	}
	
	//for receive customer msg from jpush server
//	private MessageReceiver mMessageReceiver;
//	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
//	public static final String KEY_TITLE = "title";
//	public static final String KEY_MESSAGE = "message";
//	public static final String KEY_EXTRAS = "extras";
//	
//	public void registerMessageReceiver() {
//		mMessageReceiver = new MessageReceiver();
//		IntentFilter filter = new IntentFilter();
//		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
//		filter.addAction(MESSAGE_RECEIVED_ACTION);
//		registerReceiver(mMessageReceiver, filter);
//	}
//
//	public class MessageReceiver extends BroadcastReceiver {
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
//	              String messge = intent.getStringExtra(KEY_MESSAGE);
//	              String extras = intent.getStringExtra(KEY_EXTRAS);
//	              StringBuilder showMsg = new StringBuilder();
//	              showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
//	              if (!TextUtils.isEmpty(extras)) {
//	            	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
//	              }
//	              Toast.makeText(getApplicationContext(), showMsg.toString(), Toast.LENGTH_SHORT).show();
//			}
//		}
//	}
//	
//	private void setAliasAndTags(String alias){
//		// 检查 tag 的有效性
//		String tag = "Users";
//		// ","隔开的多个 转换成 Set
//		String[] sArray = tag.split(",");
//		Set<String> tagSet = new LinkedHashSet<String>();
//		for (String sTagItme : sArray) {
//			tagSet.add(sTagItme);
//		}
//		JPushInterface.setAliasAndTags(getApplicationContext(), alias, tagSet, this);
//	}
//
//	private void setPushNotificationStyle(){
//		BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(getApplicationContext());
//		builder.statusBarDrawable = R.drawable.jpush_notification_icon;
//		builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;
//		builder.notificationDefaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
//		JPushInterface.setDefaultPushNotificationBuilder(builder);
//	}
//	
//	@Override
//	public void gotResult(int code, String alias, Set<String> tags) {
//		String logs ;
//		switch (code) {
//			case 0:
//				logs = "Set tag and alias success, alias = " + alias + "; tags = " + tags;
//				break;
//			
//			default:
//				logs = "Failed with errorCode = " + code + " alias = " + alias + "; tags = " + tags;
//		}
//		if(!TextUtils.isEmpty(logs)){
//			System.out.println("---gotResult---"+logs);
//		}
//	}
}
